package com.ddstation.hzsc_invs.warning_dispose.controller;

import com.ddstation.common.service.DataDictionaryService;
import com.ddstation.common.service.InvsItemService;
import com.ddstation.common.service.ViolationMessageService;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.crm.menu.entity.DtInvsManageInstitutionMenuEntity;
import com.ddstation.crm.menu.service.MenuService;
import com.ddstation.crud.entity.DtInvsManageInstitutionEntity;
import com.ddstation.crud.entity.MaInvsViolationMessageEntity;
import com.ddstation.exam.mapper.DtInvsInstitutionEvaluateMapper;
import com.ddstation.home_page.model.HpCommonParModel;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.util.getDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class WarningDisposeController {

    /**
     * 综合应用 => 预警处置 跳转
     * @param session
     * @return
     */
    @RequestMapping(value="invs_warning_dispose.do")
    public String warningDisposeInitEvent(
            @RequestParam(required=false)String url,
            Model model,
            HttpSession session) {

        // 从session获取基础数据
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
        if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
            return "forward:login?timeout=true"; // session 过期
        }

        if(StringUtils.isNotBlank(url)){
            model.addAttribute("url", url);
        }

        return "pc/warning_dispose/warning_dispose";
    }

    /**
     * 预警处置 公众评价
     *
     * @param
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "invs_wd_public_evaluation.do")
    public String wdPublicEvaluationInitEvent(
            Model model,
            HttpSession session) {

        // 从session获取基础数据
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
        if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
            return "forward:login?timeout=true"; // session 过期
        }

        //取开始时间
        String firstday = getDateUtil.getFirstday(null);
        model.addAttribute("dtFrom", firstday);
        //结束时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        String lastday = format.format(cale.getTime());
        model.addAttribute("dtTo", lastday);

        return "pc/warning_dispose/public_evaluation/public_evaluation";
    }

    /**
     * 预警处置 公众评价 内容加载
     * @param name
     * @param dtFrom
     * @param dtTo
     * @param page
     * @param limit
     * @param field
     * @param order
     * @param session
     * @return
     */
    @RequestMapping(value="invs_wd_public_evaluation.do/load", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> loadPublicEvaluation(
            @RequestParam(required=false) String name,
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            @RequestParam Integer page,
            @RequestParam Integer limit,
            @RequestParam (required = false) String field,
            @RequestParam (required = false) String order,
            HttpSession session){

        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("code", -1);
        ret.put("msg", "系统出错，请稍后再试！");

        try {
            SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
            DtInvsManageInstitutionEntity institution = loginData.getInstitution();
            if (loginData == null || loginData.getDoctor() == null || institution == null) {
                return ret;
            }

            HpCommonParModel _p = new HpCommonParModel();
            _p.setProvince(Integer.valueOf(institution.getProvince()));
            _p.setCity(Integer.valueOf(institution.getCity()));
            _p.setCounty(Integer.valueOf(institution.getCounty()));
            _p.setDtFrom(dtFrom);
            _p.setDtTo(dtTo);
            _p.setLimit(limit);
            _p.setPageStart(page > 0 ? (page -1) * limit : 0);
            _p.setUnderInvs(1);
            _p.setInstitutionName(name);
            if (!StringUtils.isBlank(field) && !StringUtils.isBlank(order)) {
                _p.setField(field);
                _p.setOrder(order);
            } else {
                _p.setField("total");
                _p.setOrder("DESC");
            }

            Integer count = dtInvsInstitutionEvaluateMapper.getInstitutionCount(_p);
            List<HashMap> list = dtInvsInstitutionEvaluateMapper.getInstitutionPublicEvaluations(_p);

            ret.put("code", 0);
            ret.put("msg", "");
            ret.put("count", count);
            ret.put("data", list);

        } catch (Exception e) {
            ret.put("msg", e.getMessage());
        }

        return ret;
    }

    /**
     * 预警处置 政府监督 处方违规
     *
     * @param
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "invs_wd_prescription_supervision.do")
    public String wdPrescriptionSupervisionInitEvent(
            Model model,
            HttpSession session) {

        // 从session获取基础数据
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
        if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
            return "forward:login?timeout=true"; // session 过期
        }

        //取开始时间
        String firstday = getDateUtil.getFirstday(null);
        model.addAttribute("dtFrom", firstday);
        //结束时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        String lastday = format.format(cale.getTime());
        model.addAttribute("dtTo", lastday);

        //机构类目
        List<MaDataDictionaryEntity> typeFirstList = dataDictionaryService.getCodeList("institution_type_first");
        model.addAttribute("typeFirstList", typeFirstList);

        //违规类型
        List<MaInvsViolationMessageEntity> violationMessageList = violationMessageService.selectList();
        if ( violationMessageList == null || violationMessageList.size()==0 ){
            throw new RuntimeException("master表【ma_invs_violation_message】没有数据！");
        }
        model.addAttribute("violationMessageList", violationMessageList);

        return "pc/warning_dispose/prescription_supervision/prescription_supervision";
    }

    /**
     * 预警处置 政府监督 消毒灭菌 内容加载
     * @param name
     * @param dtFrom
     * @param dtTo
     * @param page
     * @param limit
     * @param field
     * @param order
     * @param session
     * @return
     */
    @RequestMapping(value="invs_wd_prescription_supervision.do/load", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> loadWdPrescriptionSupervision(
            @RequestParam(required=false) String name,
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            @RequestParam String status,
            @RequestParam String institutionType,
            @RequestParam String msgId,
            @RequestParam Integer page,
            @RequestParam Integer limit,
            @RequestParam (required = false) String field,
            @RequestParam (required = false) String order,
            HttpSession session){

        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("code", -1);
        ret.put("msg", "系统出错，请稍后再试！");

        try {
            SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
            DtInvsManageInstitutionEntity institution = loginData.getInstitution();
            if (loginData == null || loginData.getDoctor() == null || institution == null) {
                return ret;
            }

            HpCommonParModel _p = new HpCommonParModel();
            Integer[] aTypes = {40};
            _p.setBusinessTypeList(aTypes);
            _p.setProvince(Integer.valueOf(institution.getProvince()));
            _p.setCity(Integer.valueOf(institution.getCity()));
            _p.setCounty(Integer.valueOf(institution.getCounty()));
//            _p.setProvince(12);
//            _p.setCity(208);
//            _p.setCounty(1329);
            _p.setDtFrom(dtFrom);
            _p.setDtTo(dtTo);
            _p.setLimit(limit);
            _p.setPageStart(page > 0 ? (page -1) * limit : 0);
            _p.setUnderInvs(1);
            _p.setPrescriptionInvs(1);
            _p.setInstitutionName(name);
            _p.setStatus(StringUtils.isBlank(status) ? null : Integer.valueOf(status));
            _p.setInstitutionType(StringUtils.isBlank(institutionType) ? null : institutionType);
            _p.setMsgId(StringUtils.isBlank(msgId) ? null : msgId);
            if (!StringUtils.isBlank(field) && !StringUtils.isBlank(order)) {
                _p.setField(field);
                _p.setOrder(order);
            } else {
                _p.setField("violateDt");
                _p.setOrder("DESC");
            }

            Integer count = dtHealthManageInstitutionMapper.getWdPrescriptionSupervisionCount(_p);
            List<HashMap> list = dtHealthManageInstitutionMapper.getWdPrescriptionSupervisionList(_p);

            ret.put("code", 0);
            ret.put("msg", "");
            ret.put("count", count);
            ret.put("data", list);

        } catch (Exception e) {
            ret.put("msg", e.getMessage());
        }

        return ret;
    }

    /**
     * 预警处置 政府监督 消毒灭菌
     *
     * @param
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "invs_wd_account_supervision.do")
    public String wdAccountSupervisionInitEvent(
            Model model,
            HttpSession session) {

        // 从session获取基础数据
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
        if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
            return "forward:login?timeout=true"; // session 过期
        }

        //取开始时间
        String firstday = getDateUtil.getFirstday(null);
        model.addAttribute("dtFrom", firstday);
        //结束时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        String lastday = format.format(cale.getTime());
        model.addAttribute("dtTo", lastday);

        //机构类目
        List<MaDataDictionaryEntity> typeFirstList = dataDictionaryService.getCodeList("institution_type_first");
        model.addAttribute("typeFirstList", typeFirstList);

        //违规类型
        List<MaInvsViolationMessageEntity> violationMessageList = violationMessageService.selectList();
        if ( violationMessageList == null || violationMessageList.size()==0 ){
            throw new RuntimeException("master表【ma_invs_violation_message】没有数据！");
        }
        model.addAttribute("violationMessageList", violationMessageList);

        model.addAttribute("operateType", 4); //初期停到医废处置TAB上

        // 处置方式
        model.addAttribute("deliveryTypeList", invsItemService.getInvsItemList(3));
        // 医废种类
        model.addAttribute("wasteTypeList", invsItemService.getInvsItemList(1));
        // 器械、场所区分
        model.addAttribute("instrumentTypeList", invsItemService.getInvsItemList(13));

        //获取二级菜单目录
        String firstMenuUrl = "invs_summarize.do";
        List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getWorkbenchMenus(), firstMenuUrl);
        if(secondMenus == null){
            //无访问权限【跳转地址修改】
            return "forward:login?timeout=true";
        }
        //综合查询页面特殊逻辑处理【判断是否存在所需权限】
        Map<String, Object> jurisdictionMap = new HashMap<>();
        //遍历返回一级菜单权限map
        for(DtInvsManageInstitutionMenuEntity firstMenu:loginData.getWorkbenchMenus()){
            jurisdictionMap.put(firstMenu.getUrl().replaceFirst(".do",""),true);
        }
        //遍历返回所属二级菜单权限map
        for(DtInvsManageInstitutionMenuEntity secondMenu:secondMenus){
            jurisdictionMap.put(secondMenu.getUrl().replaceFirst(".do",""),true);
        }
        model.addAttribute("jurisdictionMap", jurisdictionMap);

        return "pc/warning_dispose/account_supervision/account_supervision";
    }

    /**
     * 预警处置 政府监督 消毒灭菌 内容加载
     * @param name
     * @param dtFrom
     * @param dtTo
     * @param page
     * @param limit
     * @param field
     * @param order
     * @param session
     * @return
     */
    @RequestMapping(value="invs_wd_account_supervision.do/load", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> loadWdAccountSupervision(
            @RequestParam(required=false) String name,
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            @RequestParam String status,
            @RequestParam String institutionType,
            @RequestParam Integer page,
            @RequestParam Integer limit,
            @RequestParam (required = false) String field,
            @RequestParam (required = false) String order,
            HttpSession session){

        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("code", -1);
        ret.put("msg", "系统出错，请稍后再试！");

        try {
            SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
            DtInvsManageInstitutionEntity institution = loginData.getInstitution();
            if (loginData == null || loginData.getDoctor() == null || institution == null) {
                return ret;
            }

            HpCommonParModel _p = new HpCommonParModel();
            Integer[] aTypes = {10,20,30};
            _p.setBusinessTypeList(aTypes);
            _p.setProvince(Integer.valueOf(institution.getProvince()));
            _p.setCity(Integer.valueOf(institution.getCity()));
            _p.setCounty(Integer.valueOf(institution.getCounty()));
            _p.setDtFrom(dtFrom);
            _p.setDtTo(dtTo);
            _p.setLimit(limit);
            _p.setPageStart(page > 0 ? (page -1) * limit : 0);
            _p.setUnderInvs(1);
            _p.setInstitutionName(name);
            _p.setStatus(StringUtils.isBlank(status) ? null : Integer.valueOf(status));
            _p.setInstitutionType(StringUtils.isBlank(institutionType) ? null : institutionType);
            if (!StringUtils.isBlank(field) && !StringUtils.isBlank(order)) {
                _p.setField(field);
                _p.setOrder(order);
            } else {
                /*_p.setField("total");
                _p.setOrder("DESC");*/
            }

            Integer count = dtHealthManageInstitutionMapper.getInstitutionCount(_p);
            List<HashMap> list = dtHealthManageInstitutionMapper.getWdAccountSupervisionList(_p);

            ret.put("code", 0);
            ret.put("msg", "");
            ret.put("count", count);
            ret.put("data", list);

        } catch (Exception e) {
            ret.put("msg", e.getMessage());
        }

        return ret;
    }

    @Inject private MenuService menuService;
    @Inject private InvsItemService invsItemService;
    @Inject private DataDictionaryService dataDictionaryService;
    @Inject private ViolationMessageService violationMessageService;
    @Inject private DtInvsInstitutionEvaluateMapper dtInvsInstitutionEvaluateMapper;
    @Inject private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper;
}
